package com.atguigu.yygh.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.R;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.properties.WXProperties;
import com.atguigu.yygh.user.service.UserService;
import com.atguigu.yygh.user.utils.HttpClientUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author zhmwi
 * @Date 2021/7/17
 * @Dersciption
 */
@Api("微信登陆接口")
@Controller
@RequestMapping("/api/ucenter/wx")
public class WXApiController {

    @Autowired
    private UserService userService;

    //生成扫描登陆二维码
    @GetMapping("getLoginParam")
    @ResponseBody
    public R genQrConnect(HttpSession session) throws UnsupportedEncodingException {

        String redirectUri = URLEncoder.encode(WXProperties.WX_OPEN_REDIRECT_URL, "UTF-8");

        Map<String, Object> result = new HashMap<>();

        result.put("appid", WXProperties.WX_OPEN_APP_ID);
        result.put("redirectUri", redirectUri);
        result.put("scope", "snsapi_login");
        result.put("state", System.currentTimeMillis() + "");

        return R.ok().data(result);
    }
    //微信登陆成功后的回调方法
    @GetMapping("callback")
    public String callback(@ApiParam("登陆成功之后返回的临时凭据") String code,
                           String state, HttpSession session){
        //1.获取code的微信验证码
        System.err.println("code--"+code);
        System.err.println("state--"+code);
        //2.拿到code,请求到微信固定地址获取access_token openid
        //2.1创建基础url,参数用占位符,之后放入参数
        StringBuffer baseAccessUrlForTokenAndOpenId = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String AccessUrlForTokenAndOpenId = String.format(baseAccessUrlForTokenAndOpenId.toString(),
                WXProperties.WX_OPEN_APP_ID,
                WXProperties.WX_OPEN_APP_SECRET,
                code);
        try {
            //2.2使用工具发送请求
            String tokenInfo = HttpClientUtils.get(AccessUrlForTokenAndOpenId);
            //2.3解析字符串拿到参数
            JSONObject tokenInfoObj = JSONObject.parseObject(tokenInfo);
            String access_token = tokenInfoObj.getString("access_token");
            String openid = tokenInfoObj.getString("openid");
            //3.根据openid查询用户信息
            UserInfo userInfo = userService.getOne(new QueryWrapper<UserInfo>().eq("openid", openid));
            //4.用户信息为空 --> 注册
            if (userInfo == null){
                //根据openid+token访问微信服务端拿到用户信息并保存到数据库
        /*        "https://api.weixin.qq.com/sns/userinfo" +
                                        "?access_token=%s" +
                                            "&openid=%s";*/
                StringBuffer baseUserInfoUrl = new StringBuffer()
                        .append("https://api.weixin.qq.com/sns/userinfo")
                        .append("?access_token=%s")
                        .append("&openid=%s");
                String userInfoUrl = String.format(baseUserInfoUrl.toString(), access_token, openid);
                //获取String类型的用户信息
                String newUserInfoStr = HttpClientUtils.get(userInfoUrl);
                System.err.println("newUserInfoStr-- "+newUserInfoStr);
                //转换为json类型的用户信息
                JSONObject newUserInfoJson = JSONObject.parseObject(newUserInfoStr);
                //微信用户昵称
                String nickname = newUserInfoJson.getString("nickname");
                //微信头像
                String headimgurl = newUserInfoJson.getString("headimgurl");
                //添加到数据库
                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);
                userService.save(userInfo);
            }
            //5.用户信息不为空,说明之前注册过,走登陆
            //5.1 返回name和token字符串
            HashMap<String, String> map = new HashMap<>();
            String name = userInfo.getName();
            if (StringUtils.isEmpty(name)){
                name = userInfo.getNickName();
            }
            if (StringUtils.isEmpty(name)){
                name = userInfo.getOpenid();
            }
            map.put("name",name);

            //5.2 判断userinfo是否有手机号,如果没有 前端绑定
            //如果手机号为空,返回openid  --> 前端判断openid != ""不需要绑定手机号
            //如果手机号不为空,返回""  --> 前端判断openid == ""需要绑定手机号

            if (StringUtils.isEmpty(userInfo.getPhone())){
                //微信没有绑定手机号,openid返回正常值
                map.put("openid", userInfo.getOpenid());
            }else{
                map.put("openid","");
            }
            //5.3使用jwt生成token字符串
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token",token);
            return "redirect:http://localhost:3000/weixin/callback?token="+map.get("token")+ "&openid="+map.get("openid")+"&name="+URLEncoder.encode(map.get("name"),"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
